package com.zhongshengnetwork.rightbe.wzt.activity;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhongshengnetwork.rightbe.Adv.model.AdvertUtils;
import com.zhongshengnetwork.rightbe.Adv.model.SPManageUtils;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.CircleTransform;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.TopBarView;
import com.zhongshengnetwork.rightbe.common.activity.AppBaseActivity;
import com.zhongshengnetwork.rightbe.common.loading.KyLoadingBuilder;
import com.zhongshengnetwork.rightbe.common.utils.ToastUtil;
import com.zhongshengnetwork.rightbe.gsonmodel.CircleLangModel;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;
import com.zhongshengnetwork.rightbe.lang.activity.CircleActivity;
import com.zhongshengnetwork.rightbe.lang.activity.LangPublishActivity;
import com.zhongshengnetwork.rightbe.lang.activity.UserLangActivity;
import com.zhongshengnetwork.rightbe.login.LoginActivity;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class ClassifyAuthActivity extends AppBaseActivity implements TopBarView.onTitleBarClickListener {

    private final static int Add_Auth_User_Request = 1111;

    private TopBarView topbar;
    private int dataType = 0;
    private String dataId = "";

    private EditText search_edit;
    private Button search_button;
    private int pageindex = 0;
    private static final int Records = 20;
    private List<CircleLangModel> list;
    private ListView listview;
    private MyAdapter adapter;
    private RefreshLayout mRefreshLayout;
    private String nickname = "";
    private boolean isAdd = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_classify_auth);
        dataType = getIntent().getIntExtra("dataType", 0);
        dataId = getIntent().getStringExtra("dataId");

        topbar = (TopBarView)findViewById(R.id.topbar);
        topbar.getRightView().setVisibility(View.GONE);
        topbar.setClickListener(this);
        if (dataType == 0){
            topbar.getTitleView().setText("新增授权用户");
        }else {
            topbar.getTitleView().setText("已授权用户列表");
            topbar.getRightView().setImageResource(R.drawable.whiteadd);
            topbar.getRightView().setVisibility(View.VISIBLE);
            topbar.getRightView().setClickable(true);
            topbar.getRightView().setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent intent = new Intent(ClassifyAuthActivity.this, ClassifyAuthActivity.class);
                    intent.putExtra("dataType",0);
                    intent.putExtra("dataId", dataId);
                    startActivityForResult(intent, Add_Auth_User_Request);
                }
            });
        }
        topbar.getTitleView().setClickable(true);
        topbar.getTitleView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (list != null && list.size() > 0){
                    //listview.smoothScrollToPosition(0);
                    listview.setSelection(0);
                }
            }
        });

        search_edit = (EditText) findViewById(R.id.search_edit);
        search_button = (Button) findViewById(R.id.search_button);
        search_button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onClickSearch(v);
            }
        });
        pageindex = 0;
        if (list == null){
            list = new ArrayList<CircleLangModel>();
        }
        listview=(ListView) findViewById(R.id.classify_auth_listview);
        adapter=new MyAdapter();
        listview.setAdapter(adapter);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (list == null || list.size() == 0){
                    return;
                }
                Log.e("TAG","position="+position);
                int index = position;// - 1;
                while (index < 0){//解决部分手机点击第一条不是从1开始的问题
                    index+=1;
                }
                CircleLangModel model = list.get(index);
                Intent intent = new Intent(ClassifyAuthActivity.this, UserLangActivity.class);
                intent.putExtra(APIKey.useridKey,model.getUserid());
                intent.putExtra(APIKey.typeKey,1);
                intent.putExtra(APIKey.titleKey,model.getNickname());
                startActivity(intent);
            }
        });

        mRefreshLayout = (RefreshLayout) findViewById(R.id.refreshLayout);
        //设置 Header 为 贝塞尔雷达 样式
        mRefreshLayout.setRefreshHeader(new BezierRadarHeader(ClassifyAuthActivity.this).setEnableHorizontalDrag(true));//BezierRadarHeader
        //设置 Footer 为 球脉冲 样式
        mRefreshLayout.setRefreshFooter(new ClassicsFooter(ClassifyAuthActivity.this).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
        mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
        mRefreshLayout.setEnableRefresh(true);//启用刷新
        mRefreshLayout.setEnableLoadMore(true);//启用加载
        //刷新
        mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                //refreshlayout.finishRefresh();
                pageindex = 0;
                getData();
            }
        });
        mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                //refreshLayout.finishLoadMore();
                getData();
            }
        });
        mRefreshLayout.autoRefresh(100,300,1f,false);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == Add_Auth_User_Request && resultCode == RESULT_OK){
            mRefreshLayout.autoRefresh();
        }
    }

    public void hintKeyBoard() {
        //拿到InputMethodManager
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        //如果window上view获取焦点 && view不为空
        if (imm.isActive() && getCurrentFocus() != null) {
            //拿到view的token 不为空
            if (getCurrentFocus().getWindowToken() != null) {
                //表示软键盘窗口总是隐藏，除非开始时以SHOW_FORCED显示。
                imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
            }
        }
    }

    private void getData(){
        if (listview == null){
            return;
        }
        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                map.put("dataId", dataId);
                map.put("dataContent",CommonUtils.formatString(nickname));
                String url = "weishu/classify/auth/user/list.do";
                if (dataType == 0){
                    url = "weishu/classify/unauth/user/list.do";
                }
                HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
                    @Override
                    public void onSuccess(final String data) {
                        final CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            final List<CircleLangModel> l = GsonTools.getCircleLangModel(data);
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        list.clear();
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    if (l != null && l.size() > 0){
                                        if (l.size() >= Records){
                                            //listview.setPullLoadEnable(true);
                                            mRefreshLayout.setEnableLoadMore(true);
                                        }else {
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        list.addAll(l);
                                    }else {
                                        //listview.setPullLoadEnable(false);
                                        mRefreshLayout.setEnableLoadMore(false);
                                    }
                                    pageindex += 1;
                                    adapter.notifyDataSetChanged();
                                }
                            });

                        }else {
                            runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        //listview.stopLoadMore();
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        //listview.stopRefresh(true);
                                        mRefreshLayout.finishRefresh();
                                    }
                                    CustomApplication.showTip(commonModel, ClassifyAuthActivity.this);
                                }
                            });

                        }
                    }

                    @Override
                    public void onError(String msg) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                if (mRefreshLayout.getState() == RefreshState.Loading){
                                    //listview.stopLoadMore();
                                    mRefreshLayout.finishLoadMore();
                                }else {
                                    //listview.stopRefresh(true);
                                    mRefreshLayout.finishRefresh();
                                }
                            }
                        });
                    }
                });
            }
        }.start();

    }

    public void onClickBack(View view){
        hintKeyBoard();
        finish();
    }

    public void onClickSearch(View view){
        hintKeyBoard();
        String text = search_edit.getText().toString();
        nickname = text;
        if (mRefreshLayout != null){
            Log.e("TAG","进来获取数据了刷新界面");
                /*
                @param delayed 开始延时
                @param duration 拖拽动画持续时间
                @param dragRate 拉拽的高度比率（要求 ≥ 1 ）
                */
            mRefreshLayout.autoRefresh(100,300,1f,false);
        }
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return list.size();
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(ClassifyAuthActivity.this, R.layout.lang_circle_item,null);
            }
            View view=convertView;
            //view = LayoutInflater.from(getActivity()).inflate(R.layout.lang_circle_item, null);
            ImageView lang_circle_header = (ImageView) view.findViewById(R.id.lang_circle_header);
            ImageView privateIcon = (ImageView) view.findViewById(R.id.private_icon);
            TextView lang_circle_nickname = (TextView) view.findViewById(R.id.lang_circle_nickname);
            Button lang_circle_care = (Button) view.findViewById(R.id.lang_circle_care);
            TextView lang_circle_smart_value = (TextView) view.findViewById(R.id.lang_circle_smart_value);
            TextView lang_circle_count = (TextView) view.findViewById(R.id.lang_circle_count);
            TextView lang_comment_count = (TextView) view.findViewById(R.id.lang_comment_count);
            TextView lang_circle_care_count = (TextView) view.findViewById(R.id.lang_circle_care_count);
            CircleLangModel model = list.get(position);

            try {
                Glide.with(ClassifyAuthActivity.this).load(model.getHeader()).transform(new CircleTransform(ClassifyAuthActivity.this)).dontAnimate().into(lang_circle_header);
            }catch (Exception e){
                LangPublishActivity.uploadError("分类授权列表加载图片报错："+e.getLocalizedMessage());
            }
            if (!CommonUtils.isEmpty(model.getPrivateIcon())){
                privateIcon.setVisibility(View.VISIBLE);
                try {
                    Glide.with(ClassifyAuthActivity.this).load(model.getPrivateIcon()).transform(new CircleTransform(ClassifyAuthActivity.this)).dontAnimate().into(privateIcon);
                }catch (Exception e){
                    LangPublishActivity.uploadError("分类授权列表加载图片报错："+e.getLocalizedMessage());
                }
            }else {
                privateIcon.setVisibility(View.GONE);
            }
            lang_circle_nickname.setText(model.getNickname());
            lang_circle_care.setTag(position);

            if (dataType == 0){
                lang_circle_care.setTextColor(Color.parseColor("#87cefa"));
                lang_circle_care.setText("新增");
            }else {
                lang_circle_care.setTextColor(Color.parseColor("#FC6E51"));
                lang_circle_care.setText("移除");
            }
            lang_circle_care.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    onClickCare((int)v.getTag());
                }
            });
            lang_circle_smart_value.setText(CommonUtils.getDisplayCount(model.getLevel())+"");
            lang_circle_count.setText((model.getLangcount()-model.getLifecount())+"");
            lang_comment_count.setText(model.getWeishucount()+"");
            lang_circle_care_count.setText(model.getFanscount()+"");

            ImageView lang_member_icon = (ImageView) view.findViewById(R.id.lang_member_icon);
            if (!CommonUtils.isEmpty(model.getMemberIcon())){
                lang_member_icon.setVisibility(View.VISIBLE);
                try{
                    Glide.with(ClassifyAuthActivity.this).load(model.getMemberIcon()).
                            diskCacheStrategy(DiskCacheStrategy.RESOURCE).fitCenter().centerCrop().into(lang_member_icon);
                }catch (Exception e){
                    LangPublishActivity.uploadError("智慧排行点赞列表加载图片报错："+e.getLocalizedMessage());
                }

            }else {
                lang_member_icon.setVisibility(View.INVISIBLE);
            }

            return view;
        }

    }

    //点击关注
    private void onClickCare(final int position){
        if (list == null || list.size() == 0){
            return;
        }
        if (CommonUtils.isLogin() == false){
            Intent intent = new Intent(ClassifyAuthActivity.this, LoginActivity.class);
            startActivity(intent);
            return;
        }
        final CircleLangModel model = list.get(position);
        KyLoadingBuilder d = new KyLoadingBuilder(ClassifyAuthActivity.this);
        d.setIcon(R.drawable.loading04);
        d.setText("正在处理...");
        d.setOutsideTouchable(false);//点击空白区域是否关闭
        d.setBackTouchable(true);//按返回键是否关闭
        d.show();

        final HashMap<String, String> map = new HashMap<String, String>();
        map.put(APIKey.tokenKey, CustomApplication.loginModel.getToken());
        map.put("dataId", dataId);
        map.put("dataUserId",model.getUserid());
        String url = "weishu/classify/add/auth.do";
        if (dataType == 1){
            url = "weishu/classify/remove/auth.do";
        }
        HttpsUtils.miniAppDo(map, url, new HttpCallBack() {
            @Override
            public void onSuccess(String data) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        d.dismiss();
                        CommonModel commonModel = GsonTools.getCommonModel(data);
                        if (commonModel.getFlag().equals("1")){
                            isAdd = true;
                            ToastUtil.show(ClassifyAuthActivity.this, "处理成功");
                            list.remove(model);
                            adapter.notifyDataSetChanged();
                        }else {
                            ToastUtil.show(ClassifyAuthActivity.this, commonModel.getMsg());
                        }
                    }
                });
            }

            @Override
            public void onError(String msg) {
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        d.dismiss();
                        ToastUtil.show(ClassifyAuthActivity.this, "处理失败");
                    }
                });
            }
        });
    }


    /**
     * 点击了返回导航按钮
     */
    @Override
    public void onBackClick() {
        //Toast.makeText(LangDetailActivity.this, "你点击了左侧按钮", Toast.LENGTH_LONG).show();
        hintKeyBoard();
        if (isAdd == true && dataType == 0){
            setResult(RESULT_OK);
        }
        finish();
    }

    /**
     * 点击了右边导航按钮
     */
    @Override
    public void onRightClick() {

    }

}
